<?  // select using dd

$dd = unserialize(file_get_contents('../ajax/dd.ser'));

$rel = @$_GET['rel'];
if( !$rel ) $rel = @$_GET['dd'];
$key = (isset($_GET['key'])) ? pure_clause($_GET['key']) : null;
$pntKey = (isset($_GET['pntKey'])) ? pure_clause($_GET['pntKey']) : null;
if( $key && $pntKey ) $key = "$pntKey and $key";
else if( !$key && $pntKey ) $key = $pntKey;
$tbl_v = (isset($_GET['tbl_v'])) ? pure_code($_GET['tbl_v']) : $dd[$rel]['tbl_v'];
$order = (isset($_GET['order'])) ? pure_clause($_GET['order']) : null;
$fks = @$_GET['fks'];

if( !$rel ) ajax_exit( 'failure', "no value for rel or dd" );
if( !isset($dd[$rel]) ) ajax_exit( 'failure', "rel==$rel not found in dd" );

$query = "select * from $tbl_v ".(($key)?" where $key":'').(($order)?" order by $order":'');

$db_rcds = db_get_rcds( $query );

// foreign keys for selects
$selects = Array();
if( $fks ) foreach( $fks as $fk ) {
	$query = "select {$dd[$rel]['cols'][$fk]['fk']['pkcol']} as id,
			concat( case when active then '' else 'X:' end, {$dd[$rel]['cols'][$fk]['fk']['name']} ) as label
		from	{$dd[$dd[$rel]['cols'][$fk]['fk']['dd']]['tbl_v']}";
	//-echo "$query\n";
	$selects[$fk] = db_get_rcds( $query );
}

ajax_exit( 'success', count($db_rcds)." records pulled", Array( 'rcds'=>$db_rcds, 'fks'=>$selects ) );

?>
